<template>
  <page-header-wrapper>
    <a-card :bordered="false" class="card_top_padding" style="margin-bottom: 11px">
      <a-tabs @change="(val)=>{$router.push({name:val})}" activeKey="MchList">
        <a-tab-pane key="MchList" tab="商户列表"> </a-tab-pane>
        <a-tab-pane key="MchApply" tab="入驻审核"> </a-tab-pane>
        <a-tab-pane key="MchCommotCat" tab="所售类目"> </a-tab-pane>
        <a-tab-pane key="MchGoods" tab="入驻商品"> </a-tab-pane>
        <a-tab-pane key="MchOrder" tab="入驻订单"> </a-tab-pane>
        <a-tab-pane key="MchCashList" tab="提现申请"> </a-tab-pane>
      </a-tabs>
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="20">
            <a-col :md="4" :sm="24">
              <a-form-item label="">
                <a-input-search placeholder="店铺/用户/联系人" v-model="queryParam.keyword" />
              </a-form-item>
            </a-col>
            <a-col :md="5" :sm="24">
              <a-form-item label="全部商户">
                <a-select placeholder="全部商户" default-value="a">
                  <a-select-option value="a">全部商户</a-select-option>
                  <a-select-option value="s">支付宝</a-select-option>
                  <a-select-option value="ms">微信</a-select-option>
                  <a-select-option value="pt">公众号</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <span class="table-page-search-submitButtons" style="margin-bottom: 0">
                <a-button style="margin-right: 8px" @click="() => (this.queryParam = {})">重置</a-button>
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <a-card style="margin-top: 11px" :bordered="false" class="card_style_re">
      <div class="table-operator" style="float: right">
        <a-button type="primary" icon="plus" @click="onEdit({})">新建</a-button>
      </div>
      <a-divider />
      <s-table ref="tableList" size="default" row-key="id" :columns="columns" :data="loadData">
        <template slot="name" slot-scope="name, record">
          <a-row type="flex" align="middle">
            <a-space size="small">
              <a-space>
                <img :src="record.logo" style="width: 50px; height: 50px;border-radius:5px" alt="" />
              </a-space>
              <div>
                <div style="color: #000000">{{ name }}</div>
                <div style="font-size: 12px">所售类目：{{ record.cat }}</div>
              </div>
            </a-space>
          </a-row>
        </template>
        <template slot="nickname" slot-scope="nickname, mch">
          <a-row type="flex" align="middle">
            <a-space>
              {{ nickname }}
            </a-space>
          </a-row>
          <a-row v-if="mch.platform == 0" type="flex" align="middle">
            <a-space> 微信 </a-space>
          </a-row>
          <a-row v-if="mch.platform == 1" type="flex" align="middle">
            <a-space> 支付宝 </a-space>
          </a-row>
          <a-row v-if="mch.platform == 2" type="flex" align="middle">
            <a-space> 公众号 </a-space>
          </a-row>
        </template>
        <template slot="realname" slot-scope="realname, mch">
          <a-row type="flex" align="middle">
            <a-space>
              {{ realname }}
            </a-space>
            <a-space style="margin-left: 10px"> tel:{{ mch.tel }} </a-space>
          </a-row>
        </template>
        <template slot="created_at" slot-scope="created_at">
          <a-row type="flex" align="middle">
            <a-space>
              {{ created_at | timeFormat }}
            </a-space>
          </a-row>
        </template>
        <a-switch
          slot="is_open"
          checked-children="开启"
          un-checked-children="关闭"
          slot-scope="is_open, mch"
          :default-checked="is_open > 0"
          @change="onConfirmStatus('is_open', mch.id)"
        />
        <a-switch
          slot="is_recommend"
          checked-children="开启"
          un-checked-children="关闭"
          slot-scope="is_recommend, mch"
          :default-checked="is_recommend > 0"
          @change="onConfirmStatus('is_recommend', mch.id)"
        />
        <a-switch
          slot="is_goods_ex"
          checked-children="开启"
          un-checked-children="关闭"
          slot-scope="is_goods_ex, mch"
          :default-checked="is_goods_ex == 1"
          @change="onConfirmStatus('is_goods_ex', mch.id)"
        />
        <a-space slot="action" slot-scope="text, mch">
          <a class="ant-dropdown-link" @click="onEdit(mch)">编辑</a>
          <a-divider type="vertical" />
          <template>
            <a-dropdown>
              <a class="ant-dropdown-link" @click="(e) => e.preventDefault()"> 更多<a-icon type="down" /> </a>
              <a-menu slot="overlay">
                <a-menu-item>
                  <a @click="onSetting(mch)">设置</a>
                </a-menu-item>
                <a-menu-item>
                  <a @click="onDelete(mch.id)">删除</a>
                </a-menu-item>
              </a-menu>
            </a-dropdown>
          </template>
        </a-space>
      </s-table>
    </a-card>
    <a-modal v-model="settingVisible" :destroyOnClose="true" title="设置" @ok="handleOk" @cancel="onClose">
      <a-form action="" method="post" @submit="onSave" :form="formSetting">
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="是否开启分销">
          <a-radio-group v-decorator="['is_share']">
            <a-radio :value="0"> 关闭 </a-radio>
            <a-radio :value="1"> 开启 </a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>
    <a-modal :bodyStyle="{maxHeight:'500px',overflowY:'scroll'}" title="编辑入驻商" :width="800" :footer="null" @cancel="onClose" :destroyOnClose="true" v-model="visible">
      <template>
        <a-form action="" method="post" @submit="onSave" :form="form">
              <a-form-item :hidden="true">
                <a-input v-decorator="['id']" type="number" :step="1" />
              </a-form-item>
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="用户" hasFeedback>
                <select-user
                  @userInfo="getInfo"
                  dataType="single"
                  returnType="id"
                  selectType="user"
                  :defaultUser="defaultUser"
                >
                </select-user>
              </a-form-item>
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="商户名称" hasFeedback>
                <a-input
                  placeholder="填写商户名称"
                  v-decorator="['name', { rules: [{ required: true, message: '填写商户名称' }] }]"
                  type="text"
                  :step="1"
                />
              </a-form-item>
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="所售类目" hasFeedback>
                <a-select
                  placeholder="请选择类目"
                  v-decorator="['mch_common_cat_id', { rules: [{ required: true, message: '请选择类目' }] }]"
                >
                  <a-select-option v-for="cat in commonCat" :key="cat.id + ''">
                    {{ cat.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="联系人" hasFeedback>
                <a-input
                  placeholder="填写联系人"
                  v-decorator="['realname', { rules: [{ required: true, message: '填写联系人' }] }]"
                  type="text"
                  :step="1"
                />
              </a-form-item>
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="联系电话" hasFeedback>
                <a-input
                  placeholder="填写联系电话"
                  v-decorator="['tel', { rules: [{ required: true, message: '填写联系电话' }] }]"
                  type="text"
                  :step="1"
                />
              </a-form-item>
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="微信号" hasFeedback>
                <a-input
                  placeholder="填写微信号"
                  v-decorator="['wechat_name', { rules: [{ required: false, message: '填写微信号' }] }]"
                  type="text"
                  :step="1"
                />
              </a-form-item>
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="省市区" hasFeedback>
                <Address v-model="addressInfo"></Address>
              </a-form-item>
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="详细地址" hasFeedback>
                <a-input
                  placeholder="填写详细地址"
                  v-decorator="['address', { rules: [{ required: true, message: '填写详细地址' }] }]"
                  type="text"
                  :step="1"
                />
              </a-form-item>
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="经纬度" hasFeedback>
                <a-input-search
                  @search="select_map_visiable = true"
                  placeholder="选择经纬"
                  :readOnly="true"
                  v-decorator="['location', { rules: [{ required: true, message: '请选择经纬度' }] }]"
                >
                  <a-button slot="enterButton">选择经纬</a-button>
                </a-input-search>
              </a-form-item>
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="客服电话" hasFeedback>
                <a-input
                  placeholder="填写客服电话"
                  v-decorator="['service_tel', { rules: [{ required: true, message: '填写客服电话' }] }]"
                  type="text"
                  :step="1"
                />
              </a-form-item>
              <a-form-item
                help="商户每笔订单交易金额扣除的手续费，请填写0~1000范围的整数"
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                label="手续费(千分之)"
                hasFeedback
              >
                <a-input
                  placeholder="填写手续费"
                  v-decorator="['transfer_rate', { rules: [{ required: true, message: '填写手续费' }] }]"
                  type="number"
                  :step="1"
                />
              </a-form-item>
              <a-form-item
                help="升序，数字越小排的越靠前"
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                label="排序"
                hasFeedback
              >
                <a-input
                  placeholder="填写排序"
                  v-decorator="['sort', { rules: [{ required: true, message: '填写排序' }] }]"
                  type="number"
                  :step="1"
                />
              </a-form-item>
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="店铺Logo" hasFeedback>
                <!-- <a-input
                  placeholder="请上传店铺logo"
                  v-decorator="['logo', { rules: [ { required: false, message: '填写客服电话' } ] }]"
                  type="text"
                  :step="1"
                /> -->
                <storage-select placeholder="请上传店铺logo" v-model="mchInfo.logo"></storage-select>
              </a-form-item>
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="店铺背景（顶部）" hasFeedback>
                <!-- <a-input
                  placeholder="请上传店铺背景"
                  v-decorator="['header_bg', { rules: [ { required: false, message: '请上传店铺背景' } ] }]"
                  type="text"
                  :step="1"
                /> -->
                <storage-select placeholder="请上传店铺背景" v-model="mchInfo.header_bg"></storage-select>
              </a-form-item>
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="营业执照" hasFeedback>
                <!-- <a-input
                  placeholder="请上传营业执照"
                  v-decorator="['business', { rules: [ { required: false, message: '请上传营业执照' } ] }]"
                  type="text"
                  :step="1"
                /> -->
                <storage-select placeholder="请上传营业执照" v-model="mchInfo.business"></storage-select>
              </a-form-item>
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="身份证正面" hasFeedback>
                <!-- <a-input
                  placeholder="请上传身份证正面"
                  v-decorator="['card_front', { rules: [ { required: false, message: '请上传身份证正面' } ] }]"
                  type="text"
                  :step="1"
                /> -->
                <storage-select placeholder="请上传身份证正面" v-model="mchInfo.card_front"></storage-select>
              </a-form-item>
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="身份证反面" hasFeedback>
                <!-- <a-input
                  placeholder="请上传身份证反面"
                  v-decorator="['card_obverse', { rules: [ { required: false, message: '请上传身份证反面' } ] }]"
                  type="text"
                  :step="1"
                /> -->
                <storage-select placeholder="请上传身份证反面" v-model="mchInfo.card_obverse"></storage-select>
              </a-form-item>
          <a-form-item :gutter="[16, 30]" type="flex" align="middle">
            <a-col offset="4">
              <a-button type="primary" html-type="submit"> 保存 </a-button>
            </a-col>
          </a-form-item>
        </a-form>
      </template>
      <SelectMap v-if="select_map_visiable" :value.sync="select_map_visiable" @onOk="selectMapOk"></SelectMap>
    </a-modal>
  </page-header-wrapper>
</template>

<script>
import { list, del, save, upDown, saveSetting } from '@/api/mch/mch'
import { STable, Address } from '@/components'
import SelectUser from '@/components/SelectUser/SelectUser'
import pick from 'lodash.pick'
import SelectMap from '@/components/SelectMap/SelectMap'

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
  },
  {
    title: '店铺',
    dataIndex: 'name',
    scopedSlots: { customRender: 'name' },
  },
  {
    title: '用户',
    dataIndex: 'nickname',
    width: 100,
    scopedSlots: { customRender: 'nickname' },
  },
  {
    title: '联系人',
    dataIndex: 'realname',
    scopedSlots: { customRender: 'realname' },
  },
  {
    title: '排序',
    dataIndex: 'sort',
  },
  {
    title: '入驻时间',
    dataIndex: 'created_at',
    scopedSlots: { customRender: 'created_at' },
  },
  {
    title: '开业',
    dataIndex: 'is_open',
    scopedSlots: { customRender: 'is_open' },
  },
  {
    title: '好店推荐',
    dataIndex: 'is_recommend',
    scopedSlots: { customRender: 'is_recommend' },
  },
  {
    title: '开启商品审核',
    dataIndex: 'is_goods_ex',
    scopedSlots: { customRender: 'is_goods_ex' },
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '150px',
    scopedSlots: { customRender: 'action' },
  },
]

export default {
  name: 'MchList',
  components: {
    STable,
    SelectUser,
    Address,
    SelectMap,
  },
  data() {
    return {
      user_id: 0,
      defaultUser: null,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
      },
      queryParam: {},
      columns: columns,
      visible: false,
      form: this.$form.createForm(this),
      formSetting: this.$form.createForm(this),
      settingVisible: false,
      mchInfo: {},
      addressInfo: {},
      commonCat: [],
      select_map_visiable: false,
      loadData: (parameter) => {
        var that = this
        Object.assign(parameter, this.queryParam)
        return list(parameter).then((res) => {
          console.log(res)
          that.commonCat = res.data.common_cat
          return res.data
        })
      },
    }
  },
  activated() {
    this.$refs.tableList.$data.localDataSource = []
    this.$refs.tableList.refresh(false)
  },
  created() {},
  methods: {
    onSearch() {},
    refresh(row) {
      this.$nextTick(() => {
        this.$refs.tableList.refresh(true)
      })
    },
    onEdit(mch) {
      this.visible = true
      this.mchInfo = mch
      this.updateData()
    },
    /**
     * 渲染form表单
     */
    updateData() {
      this.addressInfo = {
        province_id: this.mchInfo.province_id,
        city_id: this.mchInfo.city_id,
        district_id: this.mchInfo.district_id,
      }
      this.mchInfo.location =
        (this.mchInfo.longitude ? this.mchInfo.longitude : 0) +
        ',' +
        (this.mchInfo.latitude ? this.mchInfo.latitude : 0)
      this.user_id = this.mchInfo.user_id
      this.defaultUser = this.mchInfo.nickname
      this.mchInfo.mch_common_cat_id = this.mchInfo.mch_common_cat_id+''
      this.$nextTick(() => {
        this.form.setFieldsValue(
          pick(this.mchInfo, [
            'id',
            'sort',
            'name',
            'realname',
            'tel',
            'name',
            'address',
            'mch_common_cat_id',
            'service_tel',
            'transfer_rate',
            'wechat_name',
            'user_id',
            'location',
          ])
        )
      })
    },
    onClose() {
      this.visible = false
      this.settingVisible = false
      this.addressInfo = {}
      this.mchInfo = {}
    },
    onSetting(mch) {
      this.settingVisible = true
      this.mchInfo = mch
      console.log(this.mchInfo)
      var that = this
      this.$nextTick(() => {
        that.formSetting.setFieldsValue(pick(that.mchInfo.setting, ['is_share']))
      })
    },
    onSave(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          var newObj = {}
          Object.assign(newObj, values, this.addressInfo)
          this.$message.loading({ content: '提交中', key: 'updatable' })
          newObj.logo = this.mchInfo.logo
          newObj.header_bg = this.mchInfo.header_bg
          newObj.business = this.mchInfo.business
          newObj.card_front = this.mchInfo.card_front
          newObj.card_obverse = this.mchInfo.card_obverse
          newObj.user_id = this.user_id
          save(newObj).then((res) => {
            if (res.code === 0) {
              this.$message.success({ content: res.msg, key: 'updatable' })
              this.$nextTick(() => {
                this.refresh()
                this.visible = false
              })
            } else {
              this.$message.error({ content: res.msg, key: 'updatable' })
            }
          })
        } else {
          for (const key in err) {
            this.$message.error(err[key].errors[0].message)
          }
        }
      })
    },
    handleOk(e) {
      e.preventDefault()
      this.formSetting.validateFields((err, values) => {
        if (!err) {
          this.$message.loading({ content: '提交中', key: 'updatable' })
          values.mch_id = this.mchInfo.id
          saveSetting(values).then((res) => {
            if (res.code === 0) {
              this.$message.success({ content: res.msg, key: 'updatable' })
              this.$nextTick(() => {
                this.refresh()
                this.onClose()
              })
            } else {
              this.$message.error({ content: res.msg, key: 'updatable' })
            }
          })
        } else {
          for (const key in err) {
            this.$message.error(err[key].errors[0].message)
          }
        }
      })
    },
    onConfirmStatus(type, id) {
      upDown({ id: id, type: type }).then((res) => {
        if (res.code === 0) {
          this.refresh()
          this.$message.success(res.msg)
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    onDelete(id) {
      this.$confirm({
        title: '是否确认删除？',
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          const hide = this.$message.loading('删除中...')
          del({ id: id }).then((res) => {
            hide()
            if (res.code === 0) {
              this.refresh()
              this.$message.success(res.msg)
            } else {
              this.$message.error(res.msg)
            }
          })
        },
      })
    },
    selectMapOk(e) {
      this.mchInfo.location = e
      var location = e.split(',')
      this.mchInfo.longitude = location[0]
      this.mchInfo.latitude = location[1]
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.mchInfo, ['location']))
      })
    },
    getInfo(val) {
      this.user_id = val
    },
  },
}
</script>
<style lang="less" scoped>
.permission-form {
  /deep/ .permission-group {
    margin-top: 0;
    margin-bottom: 0;
  }
}
.search-item {
  margin-left: 10px;
}
</style>
